package com.hd.assistant.biz.manager.impl.ordermining;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hd.assistant.biz.manager.AssistantManager;
import com.hd.assistant.biz.manager.exception.ManagerException;
import com.hd.assistant.biz.manager.ordermining.ItemCostCacheManager;
import com.hd.assistant.biz.manager.ordermining.OrderMiningManager;
import com.hd.assistant.dal.dataobject.User;
import com.hd.assistant.dal.dataobject.ordermining.ItemCost;

public class EnCacheItemCostCacheManager implements ItemCostCacheManager{
	private final static Logger log = LoggerFactory.getLogger(EnCacheItemCostCacheManager.class);
	
	private Cache cache;
	@Autowired
	private OrderMiningManager orderMiningManager;
	@Autowired
	private AssistantManager assistantManager;
	public static String ITEM_PRE="I_";
	public static String USER_PRE="U_";
	public Cache getCache() {
		return cache;
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	@Override
	public ItemCost getItemCost(String itemId) {
		String key = ITEM_PRE+itemId;
		Element e = cache.getQuiet(key);
		if(e == null){
			ItemCost value = this.getItemCostFromDB(itemId);
			if(value == null)
				return null;
			this.cache.put(new Element(key, value));
			return value;
		}else{
			return (ItemCost)e.getObjectValue();
		}
		
	}

	private ItemCost getItemCostFromDB(String itemId) {
		try {
			return orderMiningManager.getItemCostByItemId(itemId);
		} catch (ManagerException e) {
			log.error("EnCacheItemCostCacheManager : orderMiningManager.getItemCostByItemId itemId "+itemId,e);
			return null;
		}
	}

	@Override
	public User getOrderMiningUser(Long userId) {
		String key = USER_PRE+userId;
		Element e = cache.getQuiet(key);
		if(e == null){
			User user = this.getOrdermingUserFromDB(userId);
			if(user == null)
				return null;
			cache.put(new Element(key, user));
			return user;
		}else{
			return (User)e.getObjectValue();
		}
	}

	private User getOrdermingUserFromDB(Long userId) {
		try {
			User u = this.assistantManager.getUserByUserIdAndType(userId, User.Type_TAOBAO_ORDER);
			return u;
		} catch (ManagerException e) {
			log.error("EnCacheItemCostCacheManager : assistantManager.getUserByUserIdAndType userid "+userId,e);
			return null;
		}
	}

	@Override
	public void updateOrderMiningUser(Long userId) {
		String key = USER_PRE+userId;
		User user =getOrdermingUserFromDB(userId);
		cache.put(new Element(key, user));
	}

	

}
